package com.taplinker.client.im.domain;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.taplinker.client.AppConfigFactory;
import com.taplinker.client.im.protocol.CustomerInfo;
import com.taplinker.client.im.protocol.TapLinkerConversation;
import com.taplinker.core.util.LogUtil;
import com.taplinker.core.util.json.JsonIgnore;
import com.taplinker.core.util.json.JsonUtil;


public class BindData {
	private static BindData instance;
	
	public static BindData getInstance()
	{
		if (instance!=null) return instance;
		synchronized (BindData.class) {
			if (instance == null) {
				instance = restoreInstance(AppConfigFactory.getInstance().getApplication());
	 		}
		}
		return instance;
	}
	
	public static BindData restoreInstance(Context context)
	{
		instance = new BindData();
		try{
			SharedPreferences sp = context.getSharedPreferences("BIND_DATA",Context.MODE_APPEND);
			
//			instance.setConversation(ImLocalCache.getConversationById(sp.getString("conversation", "")));
//			instance.setCurrentCustomer(ImLocalCache.getCurrentCustomerById(sp.getString("conversation", "")));
			instance.setBaseUrl(sp.getString("baseUrl", ""));
			instance.setCameraFileName(sp.getString("filename", ""));
		}
		catch(Exception e)
		{
			LogUtil.d("application", "get from local is exception");
		}
		return instance;
	}
	
	private TapLinkerConversation conversation;
	private String baseUrl;
	private String cameraFileName;
	public String getCameraFileName() {
		return cameraFileName;
	}

	public void setCameraFileName(String cameraFileName) {
		this.cameraFileName = cameraFileName;
	}

	public String getBaseUrl() {
		return baseUrl;
	}

	public void setBaseUrl(String baseUrl) {
		this.baseUrl = baseUrl;
	}

	public TapLinkerConversation getConversation() {
		return conversation;
	}

	public void setConversation(TapLinkerConversation conversation) {
		this.conversation = conversation;
	}
	
	private CustomerInfo currentCustomer;
	
	public CustomerInfo getCurrentCustomer() {
		return currentCustomer;
	}

	public void setCurrentCustomer(CustomerInfo currentCustomer) {
		this.currentCustomer = currentCustomer;
	}

	@JsonIgnore
	private IBindView bindView;
	public void bind(IBindView view)
	{
		bindView = view;
	}
	
	public void unBind()
	{
		bindView = null;
	}
	
	public void noticeView(String flag)
	{
		if(bindView != null)
			bindView.handleMessage(flag);
	}
	
	public void save(Context context)
	{
		SharedPreferences sp = context.getSharedPreferences("BIND_DATA",Context.MODE_APPEND);
		Editor editor = sp.edit();
		editor.putString("conversation", getConversation().getId());
		editor.putString("customer", JsonUtil.objectToJsonStr(getCurrentCustomer()));
		editor.putString("baseUrl", getBaseUrl());
		editor.putString("filename", getCameraFileName());
		editor.commit();
		editor.clear();
	}
}
